package com.boolib.http.core.abstracts;

import cn.hutool.core.io.IoUtil;
import com.boolib.http.core.face.chain.RequestHandlerChainSupport;
import com.boolib.http.core.face.handler.RequestHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 实现Http责任链
 * @author wfq
 */
public abstract class AbstractHttpChain<T extends RequestHandler>  extends OncePerRequestFilter implements  RequestHandlerChainSupport {

    protected RequestHandler firstRequestHandler;


    protected RequestHandler lastHandler;

    @Override
    public void add(RequestHandler handler) {

        if (Objects.isNull(handler)) {
            throw new IllegalArgumentException("RequestHandler不能为空");
        }

        if(firstRequestHandler == null ){
            lastHandler = firstRequestHandler = handler;
            return ;
        }

        lastHandler.setNextRequestHandler(handler);
        lastHandler =  handler;

    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        HttpServletRequest realRequest = httpServletRequest;

        HttpServletResponse realResponse = httpServletResponse;

        if(firstRequestHandler != null){

            firstRequestHandler.fireHandler(httpServletRequest,httpServletResponse);

            if( lastHandler != null && lastHandler.isWrapper()) {
                realRequest = lastHandler.getHttpServletRequestWrapper();
                realResponse = lastHandler.getHttpServletResponseWrapper();

            }
        }

        filterChain.doFilter(realRequest, realResponse);

    }
}
